<?php

namespace app\admin\controller;

use app\comm\func\Consts;
use think\Controller;
use think\Request;
use think\Session;
use app\comm\func\CommFunc;
use think\Db;

/**
 * Class Login 登录模块
 * @package app\admin\controller
 */
class Login extends Controller
{
    /**
     * @param Request $request 登录
     * @return mixed
     */
    public function login(Request $request)
    {
        if ($request->isPost()) {
            CommFunc::emptyVerify($request->post(), ['name', 'password']);
            CommFunc::conditionAdd($condition, $request->post(), ['name', 'password']);
            $passwordLen = strlen($condition['password']);
            if ($passwordLen >= 18) {
                /* 学生登录 */
                /* 匹配姓名 */
                $findType = Db::table('student')
                    ->where('student_name', $condition['name'])
                    ->where('card', $condition['password'])->find();
                if ($findType) {
                    /* 匹配成功,进入ajax回调 */
                    CommFunc::ajaxReturn(['status' => 3, 'msg' => '学生登录成功','id'=>$findType['id']]);
                } else {
                    CommFunc::ajaxReturn(Consts::$failure);
                }

            } else {
                /* 教师、管理员登录 */
                $auth = Db::table('admin')->where('name', $condition['name'])->find();
                empty($auth) ? CommFunc::ajaxReturn(['status' => 0, 'msg' => '账号不存在']) : true;
                $auth['is_type'] == 0 ? CommFunc::ajaxReturn(['status' => 0, 'msg' => '账号被锁定']) : true;
                $auth['password'] != md5($condition['password']) ? CommFunc::ajaxReturn(['status' => 0, 'msg' => '密码不正确']) : true;
                Session::set('auth', $auth);
                CommFunc::ajaxReturn(['status' => 1, 'msg' => '登录成功', 'url' => url('admin/login/login')]);
            }
        } else {
            Session::get('auth') ? $this->redirect('admin/index/index') : true;
            return $this->fetch();
        }
    }

    /**
     * @return bool 退出
     */
    public function loginout()
    {
        Session::clear();
        $this->redirect('admin/login/login');
        return false;
    }
}